package server2;

import constants.Constants;

import javax.servlet.Servlet;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLStreamHandler;

public class ServletProcessor {
    private static final URLClassLoader LOADER;
    static {
        String repository = "file:" + Constants.WEB_ROOT + File.separator;
        URL[] urls = new URL[1];
        URLStreamHandler streamHandler = null;
        try {
            urls[0] = new URL(null, repository, streamHandler);
        } catch (MalformedURLException e) {
            System.out.println("servlet加载器初始化出错");
            e.printStackTrace();
        }
        LOADER = new URLClassLoader(urls);
    }
    public void process(Request request, Response response) {
        String uri = request.getUri();
        String servletClassName = uri.substring(uri.indexOf('/', 1) + 1);
        Servlet servletObj = null;
        try {
            Class servletClass = (LOADER.loadClass(servletClassName));
            servletObj = (Servlet)servletClass.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
            response.send404NotFound();
        }
        try {
            RequestFacade requestFacade = new RequestFacade(request);
            ResponseFacade responseFacade = new ResponseFacade(response);
            servletObj.service((ServletRequest)requestFacade, (ServletResponse)responseFacade);
        } catch (Exception e) {
            e.printStackTrace();
            response.send500ServerError();
        }

    }
}
